module.exports = (EdtApi) => {
  "use strict";
  let chatId = "", handler;
  function setTheme(theme = "light") {
      if (1 == 1) return;
      let classList = document.querySelector("html")?.classList;
      if (!classList) return;
      classList.remove("dark" == theme ? "__fb-light-mode" : "__fb-dark-mode");
      classList.add("dark" == theme ? "__fb-dark-mode" : "__fb-light-mode");
  }
  window.addEventListener('load', () => {
      setTheme(localStorage.getItem("edt-theme") || "light");
  });
  async function getChatId(times = 0) {
      let idEl = document.querySelector('div._3bwx div._4ik4._4ik5');
      let id = idEl?.textContent || "";
      if (id && id != chatId) return id;
      await EdtApi.sleep(50);
      if (times > 10) return id;
      times++;
      return getChatId(times);
  }
  function getCookie(name) {
      // 将document.cookie字符串按照; 分割成数组
      var cookies = document.cookie.split(';');
      // 修剪字符串两侧的空格
      name = name + "=";
      for (var i = 0; i < cookies.length; i++) {
          var cookie = cookies[i].trim();
          // 检查当前cookie是否是目标cookie
          if (cookie.indexOf(name) == 0)
              return cookie.substring(name.length, cookie.length);
      }
      return ""; // 如果没有找到，返回空字符串
  }
  return {
      config: {
          friendList: 'div[data-pagelet="GenericThreadListView"],div[data-pagelet="GenericBizInboxThreadListViewBody"]',
          chat: 'div.x78zum5.xdt5ytf.x2lwn1j.xeuugli.x1r8uery.x1ikap7u',
          input: 'div[data-pagelet="BizP13NInboxMessengerDetailView"] textarea[type="text"],div[data-pagelet="BizP13NInboxIGDirectDetailView"] textarea[type="text"]',
          msgBox: 'div[data-pagelet="BizInboxMessengerMessageListContainer"],div[data-pagelet="BizP13NInboxIGDirectDetailView"]',
          inMsg: 'div.x1fqp7bg div.x1cy8zhl div.x1rg5ohu.x67bb7w>div>span:not(.trans-inited)',
          outMsg: 'div.x1fqp7bg div.xuk3077 div.x1rg5ohu.x67bb7w>div>span:not(.trans-inited)',
          sendBtn: 'div.x78zum5.xdt5ytf.x2lwn1j.xeuugli div.x6s0dn4.x78zum5.x2lwn1j.xeuugli>div.xogfrqt.x1jchvi3>div[role="button"]',
          setting: 'div.x78zum5.xdt5ytf.x2lwn1j.xeuugli div.x6s0dn4.x78zum5.x2lwn1j.xeuugli>div.x1rg5ohu.x67bb7w:nth-child(1)',
          tips: {
              in: 'div.x1swdo50.xw2csxc.x1odjw0f._5bpf div._3bwx',
              out: 'div.xh8yej3>div.xh8yej3>div.x78zum5.xdt5ytf.x2lwn1j.xeuugli'
          },
          placeholder: {
              selector: 'div[data-pagelet="BizP13NInboxMessengerDetailView"] textarea[type="text"],div[data-pagelet="BizP13NInboxIGDirectDetailView"] textarea[type="text"]',
              attr: 'placeholder'
          },
          extra: {//其他会触发对话框变动的情况处理
              selector: 'ul[role="listbox"],span[role="gridcell"]>div>div[role="button"],div[data-visualcompletion="ignore-dynamic"],nav ul li a[role="link"],div[role="group"]>a[role="link"]',
              level: 20,
              delay: 1000,
          },
          inputType: "input",
          initChat: true,
          autoCount: 20,
          mainRequest: true
      },
      init(handle) {
          handler = handle;
          EdtApi.queryWait({ selector: 'nav._ago8 ul._6no_', timeout: 60000 }).then(view => {
              view?.addEventListener('click', () => {
                  this.initChat();
              });
          }).catch(() => { });
      },
      setTheme({ theme }) {
          localStorage.setItem("edt-theme", theme);
          setTheme(theme);
      },
      initChat() {
          EdtApi.queryWait({ selector: this.config.friendList, timeout: 60000 }).then(view => {
              view && handler?.initChat(null);
          }).catch(() => { });
      },
      getUnread() {
          let el = document.querySelector('div[data-visualcompletion="ignore-dynamic"] div[role="group"]>a:nth-child(1) span.x3nfvp2.xmix8c7.x1n2onr6>span');
          let text = "0";
          if (el) {
              text = el?.textContent || "0";
              return text ? parseInt(text) : 0;
          }
          el = document.querySelector('div[role="listitem"] div.xet2fuk.xvijh9v span.x3nfvp2.xmix8c7.x1n2onr6>span');
          text = el?.textContent || "0";
          return text ? parseInt(text) : 0;
      },
      getChatInfo() {
          return new Promise((resolve) => {
              EdtApi.sleep(300).then(async () => {
                  chatId = await getChatId();
                  resolve({ id: chatId, isGroup: false })
              }).catch(() => { });
          });
      },
      getChatTitle() {
          let titleEl = document.querySelector('div._3bwx div._4ik4._4ik5');
          return titleEl?.textContent || "";
      },
      getText(msgBox) {
          try {
              let texts = [], children = msgBox?.childNodes;
              children?.forEach(item => {
                  if ("BR" == item.tagName) {
                      texts.push("\n");
                  } else if ("SPAN" == item.tagName) {
                      item.childNodes?.forEach(child => {
                          if ("IMG" == child.tagName) {
                              texts.push(child.getAttribute("alt"));
                          } else texts.push(item.textContent);
                      });
                  }
              });
              return texts.join("");
          } catch (error) {
              console.error(error);
          }
          return "";
      },
      getIptMsg(inputEl) {
          if (!inputEl) return '';
          if ("TEXTAREA" == inputEl.tagName) return inputEl.value || "";
          return "";
      },
      getUserInfo() {
          try {
              let avatarEl = document.querySelector('div.x1rg5ohu.x1n2onr6.x3ajldb.x1ja2u2z>svg.x3ajldb>g>image');
              let avatar = avatarEl?.getAttribute("xlink:href") || "";
              let account = " ";
              let userName = getCookie("c_user") || "";
              return {
                  avatar,
                  userName,
                  account,
                  toDataUrl: true
              };
          } catch (error) {
              return null;
          }
      }
  }
};